#include <iostream>
#include <pthread.h>
#include <string>
#include <unistd.h>

int shared_data = 0;

pthread_rwlock_t rwlock;

void *Writer(void *args) // 参数是线程的编号
{
    int number = *(int *)args;
    while (true)
    {
        pthread_rwlock_wrlock(&rwlock);
        shared_data += 1;
        std::cout << "写者-" << number << "正在写入，新的数据是：" << shared_data << std::endl;
        sleep(2); // 模拟写入数据需要的时间
        pthread_rwlock_unlock(&rwlock);
    }
    delete (int *)args;
    return nullptr;
}

void *Reader(void *args)
{
    int number = *(int *)args;
    while (true)
    {
        pthread_rwlock_rdlock(&rwlock);
        std::cout << "读者-" << number << "正在读数据，数据是：" << shared_data << std::endl;
        //sleep(1); // 模拟读取数据需要的时间
        pthread_rwlock_unlock(&rwlock);
        sleep(1); // 模拟读取数据需要的时间
    }
    delete (int *)args;
    return nullptr;
}

int main()
{
    pthread_rwlock_init(&rwlock, nullptr);

    const int writer_num = 1;
    const int reader_num = 5;
    const int total = writer_num + reader_num;

    pthread_t threads[total];

    
    for (int i = 0; i <reader_num; i++)
    {
        int *id = new int(i);
        pthread_create(&threads[i], nullptr, Reader, id);
    }

    for (int i = reader_num; i < total; i++)
    {
        int *id = new int(i-reader_num);
        pthread_create(&threads[i], nullptr, Writer, id);
    }


    for (int i = 0; i < total; i++) // 等待所有线程执行完毕
    {
        pthread_join(threads[i], nullptr);
    }

    pthread_rwlock_destroy(&rwlock);

    return 0;
}
